package com.luck.easyfoodbatch.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.mvp.mine.PayYearFeeModel;
import com.luck.easyfoodbatch.mvp.mine.PayYearFeePresenter;
import com.luck.easyfoodbatch.mvp.mine.PayYearFeeView;
import com.luck.easyfoodbatch.mvp.model.YearM;
import com.luck.easyfoodbatch.pay.PayResult;
import com.luck.easyfoodbatch.simcpux.Constants;
import com.luck.easyfoodbatch.util.AlipayUtil;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.Tools;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class AnnualFeeActivity extends BaseActivity implements PayYearFeeView {
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.iv_money)
    ImageView ivMoney;
    @BindView(R.id.tv_activation)
    TextView tvActivation;
    @BindView(R.id.ll_layout)
    LinearLayout llLayout;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_vip_status)
    TextView tv_vip_status;
    @BindView(R.id.rl_wechat)
    RelativeLayout rl_wechat;
    @BindView(R.id.rl_apply)
    RelativeLayout rl_apply;
    @BindView(R.id.iv_wechat)
    ImageView iv_wechat;
    @BindView(R.id.iv_apply)
    ImageView iv_apply;
    @BindView(R.id.tv_money)
    TextView tv_money;
    private int type = 0;
    private IWXAPI api;
    private int pay_type = 2;
    private static final int SDK_PAY_FLAG = 1;
    private PayYearFeeModel yearFeeModel;
    private User user;
    private int created_at = 0;
    private Handler MyHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        ivMoney.setImageResource(R.mipmap.vip_act_1x);
                        String time = String.valueOf(System.currentTimeMillis()).substring(0, 10);
                        tvActivation.setText("激活于" + Tools.SubTime3(time));
                        tvTitle.setText("年费");
                        tv_vip_status.setText("已激活");
                        tvActivation.setVisibility(View.VISIBLE);
                        llLayout.setVisibility(View.GONE);
                        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                        user.setIs_year_fee(1);
                        App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                        T.showToast(mContext, "支付成功");
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(mContext, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(mContext, "支付失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }

            }
        }
    };

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 微信支付成功
            if (intent.getAction().equals("action.finishApplyActivity")) {
                ivMoney.setImageResource(R.mipmap.vip_act_1x);
                String time = String.valueOf(System.currentTimeMillis()).substring(0, 10);
                tvActivation.setText("激活于" + Tools.SubTime3(time));
                tvTitle.setText("年费");
                tv_vip_status.setText("已激活");
                tvActivation.setVisibility(View.VISIBLE);
                llLayout.setVisibility(View.GONE);
                User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
                user.setIs_year_fee(1);
                App.getInstance().saveObject(user, HttpUtil.USER_KEY);
                T.showToast(mContext, "支付成功");
                finish();
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_annual_fee, "支付年费", MODE_BACK_NAVIGATION);
        ButterKnife.bind(this);
        registerReceiver(receiver, "action.finishApplyActivity");
        type = 1;
        yearFeeModel = new PayYearFeePresenter(this, mContext);
        yearFeeModel.requestPayYearFee(pay_type);
        api = WXAPIFactory.createWXAPI(this, null);
        api.registerApp(Constants.APP_ID);
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if (user != null) {
            int is_year_fee = user.getIs_year_fee();//是否交年费 0为未交，1为已交
            switch (is_year_fee) {
                case 0:
                    tvActivation.setVisibility(View.GONE);
                    llLayout.setVisibility(View.VISIBLE);
                    break;
                case 1:
                    ivMoney.setImageResource(R.mipmap.vip_act_1x);
                    int last_year_fee_time = user.getLast_year_fee_time();
                    if (last_year_fee_time > 0) {
                        tvActivation.setText("激活于" + Tools.SubTime3(last_year_fee_time + ""));
                    } else {
                        tvActivation.setText("");
                    }
                    tvTitle.setText("年费");
                    tv_vip_status.setText("已激活");
                    tvActivation.setVisibility(View.VISIBLE);
                    llLayout.setVisibility(View.GONE);
                    break;
            }
        }
    }

    @OnClick({R.id.rl_apply, R.id.rl_wechat, R.id.btn_ok})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_ok:
                showProgressDialog(getString(R.string.app_loading));
                yearFeeModel.requestPayYearFee(pay_type);
                break;
            case R.id.rl_wechat:
                pay_type = 2;
                type = 0;
                iv_wechat.setImageResource(R.mipmap.select_sel_1x);
                iv_apply.setImageResource(R.mipmap.select_def_1x);
                break;
            case R.id.rl_apply:
                pay_type = 1;
                type = 0;
                iv_wechat.setImageResource(R.mipmap.select_def_1x);
                iv_apply.setImageResource(R.mipmap.select_sel_1x);
                break;
        }
    }

    @Override
    public void payYearFeeSuccess(YearM model) {
        if (model != null) {
            if (model.getStatus() == HttpUtil.RESULT_OK) {
                // 订单生成成功 支付 1支付宝2微信
                YearM.DataBean bean = model.getData();
                if (type == 1) {
                    tv_money.setText(bean.getOrder_price() + "元");
                    type = 0;
                } else {
                    String params = bean.getParams();
                    if (!Tools.isNull(bean.getOrder_price())) {
                        if (!bean.getOrder_price().equals("0")) {
                            switch (pay_type) {
                                case 1:
                                    new AlipayUtil(AnnualFeeActivity.this, params, MyHandler);
                                    break;
                                case 2:
                                    wechatApply(bean);
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 微信支付
     *
     * @param bean
     */
    private void wechatApply(YearM.DataBean bean) {
        try {
            PayReq req = new PayReq();
            req.appId = bean.getAppid();
            req.partnerId = bean.getPartnerid();
            req.prepayId = bean.getPrepayid();
            req.nonceStr = bean.getNoncestr();
            req.timeStamp = bean.getTimestamp() + "";
            req.packageValue = bean.getPackageX();
            req.sign = bean.getSign();
            Toast.makeText(this, "正在发起微信支付，请稍候...", Toast.LENGTH_SHORT).show();
            // 在支付之前，如果应用没有注册到微信，应该先调用IWXMsg.registerApp将应用注册到微信
            api.registerApp(Constants.APP_ID);
            api.sendReq(req);
        } catch (Exception e) {
            Log.e("PAY_GET", "异常：" + e.getMessage());
        }
    }

    @Override
    public void httpStatusError() {

    }

    @Override
    public void hideLoading() {
        hideShowProgress();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
        }
    }
}
